package jgl.vajra.operator.part.vehicle.pop;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.orhanobut.logger.Logger;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.operator.R;
import jgl.vajra.operator.bean.OrderDetailsBean;
import jgl.vajra.operator.bean.OrderPaymentDetailsBean;
import jgl.vajra.operator.bean.RestStartBean;
import jgl.vajra.operator.databinding.PopRestStartBinding;
import jgl.vajra.operator.manager.AccountManager;
import jgl.vajra.operator.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.operator.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.operator.widget.manager.RxJavaHttpManager;
import jgl.vajra.operator.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.operator.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.operator.widget.utils.ToastUtils;
import jgl.vajra.operator.widget.utils.UIUtils;

public class RestStartPop implements BaseBindingItemPresenter<RestStartBean> {
    private final OrderPaymentDetailsBean data;
    private WeakReference<FragmentActivity> activityWeakReference;
    private PopupWindow menuPop;
    private View mPopRootView;
    private PopRestStartBinding mBinding;
    private final Activity mContext;
    private RestStartListener listener;
    private SingleTypeBindingAdapter adapter;
    private List<RestStartBean> list = new ArrayList<>();
    private int status = -1;
    private String remark;

    public RestStartPop(FragmentActivity activity, OrderPaymentDetailsBean data) {
        mContext = activity;
        this.data = data;
        activityWeakReference = new WeakReference<>(activity);
    }

    private void initPopupWindow() {
        mPopRootView = View.inflate(UIUtils.getContext(), R.layout.pop_rest_start, null);
        mBinding = DataBindingUtil.bind(mPopRootView);
        if (mBinding != null)
            mBinding.setView(this);

        menuPop = new PopupWindow(mPopRootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        menuPop.setOutsideTouchable(false);
        menuPop.setBackgroundDrawable(new BitmapDrawable());
        menuPop.setFocusable(true);// 点击空白处时，隐藏掉pop窗口
        menuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Logger.d("------onDismiss");
                //popupwindow消失的时候恢复成原来的透明度
                // backgroundAlpha(R.color.gray_f8);
                backgroundAlpha(1f);

            }
        });

        //机械类型
        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        FlexboxLayoutManager flManager = new FlexboxLayoutManager(mContext);
        flManager.setFlexWrap(FlexWrap.WRAP);
        //设置主轴的方向
        flManager.setFlexDirection(FlexDirection.ROW);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(flManager);
        adapter = new SingleTypeBindingAdapter(mContext, null, R.layout.item_rest_start);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        RetrofitJsonManager.getInstance().getApiService().getRestStartData(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<List<RestStartBean>>(true, null) {
                    @Override
                    public void _onNext(List<RestStartBean> data) {
                        list = data;
                        adapter.refresh(list);
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                    }
                });
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        if (activityWeakReference.get() == null) return;
        if (activityWeakReference != null) {
            WindowManager.LayoutParams lp = activityWeakReference.get().getWindow().getAttributes();
            lp.alpha = bgAlpha; //0.0-1.0
            activityWeakReference.get().getWindow().setAttributes(lp);
        }
    }

    public void showPopupWindow(View v) {
        if (menuPop == null)
            initPopupWindow();
        int[] location = new int[2];
        v.getLocationOnScreen(location);  //获取控件的位置坐标
        //获取自身的长宽高
        mPopRootView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        //backgroundAlpha(R.color.titleBackgroundColor);
        backgroundAlpha(0.8f);
        menuPop.showAtLocation(v, Gravity.BOTTOM, 0, 0);  //显示指定控件的上方
    }

    public boolean isShowing() {
        return menuPop != null && menuPop.isShowing();
    }

    public void dismiss() {
        if (isShowing()) {
            menuPop.dismiss();
        }
    }

    //确定
    public void onDetermine() {
        if (status == -1) {
            ToastUtils.showShort("请选择中途休息原因");
            return;
        }
        if (status == 7)
            remark = mBinding.etRemark.getText().toString().trim();
        if (listener != null) {
            dismiss();
            listener.onDetermine(status, remark);
        }
    }

    public void setRestStartListener(RestStartListener listener) {
        this.listener = listener;

    }

    public interface RestStartListener {
        void onDetermine(int status, String remark);
    }

    @Override
    public void onItemClick(int position, RestStartBean itemData) {
        if (itemData.isClick)
            return;
        for (int i = 0; i < list.size(); i++) {
            list.get(i).isClick = false;
        }
        list.get(position).isClick = true;
        adapter.refresh();

        status = itemData.status;
        remark = itemData.description;

        if (itemData.status == 7) {
            mBinding.etRemark.setVisibility(View.VISIBLE);
        } else {
            mBinding.etRemark.setVisibility(View.GONE);
        }
    }
}